<?php
@session_start();
if (isset($_SESSION['username']))
{
    // echo date("m-y-d");
}
else
{
    header("location:../../index.php");
}

$command = isset($_GET['command'])? $_GET['command'] : null;
$user_id = isset($_GET['user_id'])? $_GET['user_id'] : null;
$app_id  = isset($_GET['appID'])? $_GET['appID'] : null;

$current_link = $_SERVER['PHP_SELF'];

// xu ly viec xoa mot user
if($user_id && $command == 'delete')
{
    require_once("../../model/user.php");

    $list_user = new User();
    // lay role cua $user_id
    $role = $list_user->getUserRole_With_userId($user_id);

    // neu khong phai admin thi cho xoa
    if($role != "admin")
    {
        $list_user->delete_user_with_id($user_id);
        header("location: $current_link");
    }
}

// xu ly viec xoa mot ung dung
if($app_id && $command == "Delete")
{
    require_once("../../model/application.php");

    $list_app = new Applications();

    echo "Delete?"; exit(); // demo thoi khong xoa that dau

    $list_app->delete_Item_By_Id($app_id);
    header("location: $current_link");
}

// var_dump($_SERVER);exit();
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8"/>
    <script src="../../assets/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="../../assets/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">

        // kỹ thuật xử lý di chuyển qua lại giữa các tab
        function del_contact_by_id(contact_id)
        {
            if(window.confirm("Bạn có chắc muốn xóa"))
            {
                $.ajax({
                    url: "../../controller/controller_delContact.php",
                    type: "POST",
                    data: "contact_id=" + contact_id,
                    dataType: "html",
                    success: function(response)
                    {
                        setTimeout(function(a) {
                            a();
                        }, 1000, get_list_contact); // goi ham get_list_contact
                    }
                });
            } else {
                return;
            }

        }
        // xoa mot hoa don ra khoi he thong
        function del_invoice_by_id(invoice_id)
        {
            if(window.confirm("Delete this invoice?"))
            {
                $.ajax({
                    url: "../../controller/controller_deleteInvoice.php",
                    type: "POST",
                    dataType: "json",
                    data: "invoice_id=" + invoice_id,
                    success: function(res)
                    {
                        if(res.error) alert(res.msg);
                        else {
                            $(".list-invoice .invoice-" + invoice_id).remove();
                        }
                    } 
                });                
            } else {
                return; // khong lam gi ca he thong dung yen
            }
        }
        // menu_tab di chuyen
        function menu_tab(menu_name)
        {
            menu_name.onclick(function(e){
                $(".active").removeClass("active");
                $(this).hide();
                $(this).addClass("active");
                var title = $(this).attr("title");
                $("#" + title).show();
            });
        }

        function confirmDirect(e)
        {
            if(!confirm("Bạn có chắc muốn xóa?")) return false;
        }

        // hiển thị danh sách user
        function list_user()
        {
            $.ajax({
                type: "post",
                url: "../../controller/controller_listUser.php",
                data: "",
                dataType: "json",
                success: function(content, status)
                {
                    console.log(content);

                    var html = "<table border='0' class='table table-striped'>";
                    html += "<thead>";
                        html += "<th>Mã user</th>";
                        html += "<th>Tên</th>";
                        html += "<th>Quyền</th>";
                        html += "<th>Địa chỉ</th>";
                        html += "<th>Giới tính</th>";
                        html += "<th colspan='2'>Tác vụ</th>";
                    html += "</thead>";
                    $.each(content, function (key, value) {
                        html += "<tr>";
                        html += "<td>" + value.user_id + "</td>";
                        html += "<td>" + value.username + "</td>";
                        // doan nay ta khong cho hien thi admin trong danh sach
                        html += "<td>" + value.user_role + "</td>";
                        html += "<td>" + value.user_address + "</td>";

                        if (value.user_sex == 1) {
                            html += "<td>" + "Nam" + "</td>";
                        } else {
                            html += "<td>" + "Nữ" + "</td>";
                        }

                        html += "<td><a href='edit_user.php?user_id=" + value.user_id + "'>Edit</a></td>";

                            html += "<td><a class='del-user' href='?user_id=" + value.user_id + "&command=delete'>Delete</a></td>";

                        html += "</tr>";
                    });

                    html += "</table>";

                    var userList = $("#user_list");
                    userList.html(html);
                    $('.del-user', userList).click(confirmDirect); // tim class trong dom user list

                    $("tr:even").css("background-color", "#f1f1f1");
                }
            });
        } // END list_user()

        function get_list_contact()
        {
            $.ajax({
                url: "../../controller/controller_listContact.php",
                type: "POST",
                data: "",
                dataType: "html",
                success: function(response, status)
                {
                    $("#content3").show().html(response);
                }
            });
        }

        // Xử lý phân trang với ajax
        function gotoPage(num_pages)
        {
            $.ajax({
                type: "GET",
                data: "num_pages=" + num_pages,
                dataType: "html",
                url: "../../controller/controller_listApplication.php",
                success: function(response){
                    $("#application_list").html(response);
                    var app_list = $("#application_list");
                    $('.del_app', app_list).click(confirmDirect);
                }
            });
        }
        // xu ly viec thong ke luot tai ung dung
        function report_number_download()
        {
            $.ajax({
                url: "../../controller/controller_report_download.php",
                type: "post",
                data: "",
                dataType: "html",
                success: function(response, status)
                {
                    $("#report").html(response);
                }
            });
        }
        function list_user_download(app_name)
        {
            $.ajax({
                url: "../../controller/controller_detailDownload.php",
                type: "post",
                data: "app_name=" + app_name,
                dataType: "html",
                success: function(response, status)
                {
                    console.log(response);                    
                    $("#detail_download").html(response);  
                    console.log($("#detail_download"));                      
                }
            });
        }
        // xử lý việc thêm ứng dụng
        function form_validation(form_name)
        {
            form_name.validate({
                rules :{
                    app_name: {
                        required: true,
                        minlength: 6
                    },
                    app_status: {
                        required: true
                    },
                    description: {
                        required: true
                    }
                },
                messages: {
                    app_name :{
                        required: "Mời nhập tên ứng dụng",
                        minlength: "Tối thiểu phải là 6 kí tự"
                    },
                    app_status: {
                        required: "Phải lựa chọn status ứng dụng"
                    },
                    description: {
                        required: "Mời bạn nhập vào mô tả sản phẩm"
                    }
                }
            });
        }
        // tim kiem user theo dia chi va ten username
        function search_user_by_address_username(username, address)
        {
            $.ajax({
                url: "../../controller/controller_searchUser.php",
                type: "POST",
                dataType: "html",
                data: "username=" +username + "&address="+ address,
                success: function(response)
                {
                    console.log(response);                    
                    $("#list_user_searched").html(response);

                }
            });
        }
        $("document").ready(function () {
            // catch event click in one of tab
            $(".tab").click(function (e) {
                $(".active").removeClass("active");

                $(this).addClass("active"); // them thuoc tinh active cho tung content

                $(".content").hide(); // anh noi dung cua tung content di

                var title = $(this).attr("title");
                var request = $.ajax({
                    type: "post",
                    dataType: "json",
                    data: {
                        "title": title
                    },
                    url: "../../controller/processContent.php"
                });
                request.done(function (response, status) {
                    console.log(response.content);
                    console.log(status);
                    var content = response.content;
                    // alert(content); // content in each tab
                    if (title === "content3") {
                       get_list_contact();
                    } else if (title === "content1") { // neu danh sach nguoi dung
                        $("#"+ title).show();
                    } else if(title == "content4")
                    {
                        window.location.href = "../../index.php";
                    }
                    else {
                        $("#" + title).show();
                    }


                });
            });

            $(".tab1").click(); // mac định là tab1 sẽ được click

            // xu ly noi dung cua content1
            $(".side-tab-c1").click(function(e){
                $(".active").removeClass("active");
                $(this).addClass("active");

                $(".side-tab-c1-content").hide(); // an het content di

                var title = $(this).attr("title");
                if(title == "user_list")
                {
                    list_user();
                }
                $("#"+title).show();
            });

            // xu ly noi dung cua content2
            var side_tab_c2 = $(".side-tab-c2");
            side_tab_c2.click(function(e){
                $(".active").removeClass("active");

                $(this).addClass("active");

                $(".side-tab-c2-content").hide();

                var title = $(this).attr("title");

                if(title == "application_list")
                {
                    // Liet ke danh sach san pham voi phan trang
                    gotoPage(0);
                }
                else if(title == "parent_report")
                {
                    report_number_download();
                }
                $("#"+ title).show();
                // validate thêm ứng dụng
                var $add_form = $("#add_form");
                form_validation($add_form);
            });

            // xu ly tim kiem user
            $("#btn_search_user").click(function(e){
                if(!$(this).hasClass("clicked")){
                    $(this).addClass("clicked");
                    var username  = document.form2.username.value;
                    var tinhthanh = document.form2.tinhthanh.value;

                    setTimeout(function(){
                        search_user_by_address_username(username, tinhthanh);
                    },500);
                    $(this).removeClass("clicked");
                }
            });


        }); // END load DOM
    </script>

    <link rel="stylesheet" href="style_admin.css" type="text/css"/>
    <link rel="stylesheet" href="../../assets/css/style.css" type="text/css"/>
</head>
<body>
<div id="wrapper">
    <div id="header">
        <img src="../../upload/administrator_icon.jpg"/>
        Xin chào Admin!
    </div>
    <div id="tab-menu">
        <div id="list-menu">

            <ul>
                <li><a title="content1" href="javascript:void(0)" class="tab tab1">Quản lý user</a></li>
                <li><a title="content2" href="javascript:void(0)" class="tab tab2">Quản lý ứng dụng</a></li>
                <li><a title="content3" href="javascript:void(0)" class="tab tab3">Quản lý liên hệ</a></li>
                <li><a title="content6" href="javascript:void(0)" class="tab tab6">Quản lý hóa đơn</a></li>
                <li><a title="content4" href="javascript:void(0)" class="tab tab4">Home Page</a></li>
                <li><a title="content5" href="../logout.php" class="tab tab5">Log out</a></li>
            </ul>

        </div>
        <div id="clearFix"></div>


        <div id="parent">

            <!-- content 1 Quan li danh sach user -->
            <div id="content1" class="content">
                <ul id="user_manager">
                    <li title="user_list" class="side-tab-c1 user_list">Liệt kê danh sách user</li>
                    <li class="side-tab-c1" title="search_user">Tìm kiếm user</li>
                </ul>

                <div class="side-tab-c1-content" id="user_list">

                </div> <!-- END user_list -->

                <div class="side-tab-c1-content" id="search_user" style="display:none">                
                    <form name="form2" class="form-inline">

                        <div class="col-xs-4">
                            <u>Chọn tỉnh thành:</u>
                            <select class="form-control" name="tinhthanh">
                                <option value="">Chọn tỉnh thành</option>
                                <?php
                                // khai bao doc xml
                                $obj_xml = simplexml_load_file("list_address.xml"); // doc du lieu xml
                                for($i = 0; $i < $obj_xml->count(); $i++)
                                    echo "<option value='{$obj_xml->item[$i]->tinh}'>".$obj_xml->item[$i]->tinh."</option>";
                                ?>
                            </select>
                        </div>
                        <div class="col-xs-4">
                            <u>Nhập từ khóa:</u>
                            <input type="text" class="form-control input-xs" name="username"/>
                        </div>
                        <div class="col-xs-4">
                            <br>
                            <input type="button" class="btn-default btn" id="btn_search_user" value="search!"/>
                        </div>
                    </form>

                    <div class="clear-fix"></div>
                    <div id="list_user_searched">

                    </div>
                </div> <!-- END search user -->
            </div> <!-- END content1 -->

            <!-- content 2 Quan li danh sach cac ung dung -->
            <div id="content2" class="content">

                <ul id="app_manager">
                    <li class="side-tab-c2 add_function" title="add_more_application">Thêm ứng dụng</li>
                    <li class="side-tab-c2 list_function" title="application_list">Liệt kê danh sách ứng dụng</li>
                    <li class="side-tab-c2 report_download" title="parent_report">Thống kê lượt tải</li>

                </ul>
                <!-- danh sách các ứng dụng -->
                <div id="application_list" class="side-tab-c2-content"></div>

                <!-- Thêm ứng dụng -->
                <div id="add_more_application" class="side-tab-c2-content">
                    <p>Thêm ứng dụng</p>
                    <form class="form-horizontal" id="add_form" enctype="multipart/form-data" method="post" action="../../controller/controller_uploadApp.php">
                        <!-- appName -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Tên ứng dụng:</label>
                            <div class="col-xs-3">
                                <input type="text" name="app_name" id="app_name" class="form-control input-sm" required />
                            </div>
                        </div>

                        <!-- app_status -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Status:</label>
                            <div class="col-xs-3">
                                <select class="form-control" name="app_status" id="app_status" required>
                                    <option value="free">Free</option>
                                    <option value="license">License</option>
                                </select>
                            </div>
                        </div>
                        <!-- image -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Upload:</label>
                            <div class="col-xs-3">
                                <input type="file" name="file_upload" id="file_upload" value="Browser" required />
                            </div>
                        </div>
                        <!-- desc -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Mô tả:</label>
                            <div class="col-xs-3">
                                <textarea class="form-control" name="description"></textarea>
                            </div>
                        </div>
                        <!-- submit -->
                        <div class="form-group">
                            <label class="col-sm-2 control-label"></label>
                            <div class="col-xs-3">
                                <input type="submit" name="submit" value="Thêm" id="appstatus" class="btn-default btn btn-sm"/>
                            </div>
                        </div>
                    </form>
                </div> <!-- END them ung dung -->
                
                <!-- thống kê số lượt tải ứng dụng -->
                <div class="side-tab-c2-content" id="parent_report">
                    <div id="report"></div>
                    <div id="detail_download"></div>
                </div> <!-- END thong ke luot tai -->
                
                
            </div> <!-- END content 2 Quản lý ứng dụng -->

            <!-- content 3 -->
            <div id="content3" class="content">
                Content 3
            </div> <!-- END content 3 -->

            <!-- content 4 -->
            <div id="content4" class="content">
                Content 4
            </div> <!-- END content 4 -->


            <div id="content5" class="content">
                Content 5
            </div> <!-- END content5 -->

            <!-- phan xu ly hoa don -->
            <div id="content6" class="content">
                <?php include("../../controller/controller_processInvoice.php");?>
            </div>
        </div>
    </div>
    
    <?php include("../../footer.php"); // chen footer vao admin page?>
</div>

</body>
</html>